#include "visbasecollection.h"
#include "dynamicvalue.h"

VisBaseCollection::VisBaseCollection(QGraphicsItem *parent) :
    QGraphicsWidget(parent)
{
    isTargeting = false;

    dynX = new DynamicValue( 0.0 );
    dynY = new DynamicValue( 0.0 ); //init 0, no need to store anything yet
    dynWidth = new DynamicValue( 50.0 );
    dynHeight = new DynamicValue( 50.0 );
}

VisBaseCollection::~VisBaseCollection()
{
    if( dynX != NULL )
        delete dynX;
    if( dynY != NULL )
        delete dynY;
    if( dynWidth != NULL )
        delete dynWidth;
    if( dynHeight != NULL )
        delete dynHeight;
}

//dynamic targeting to new position
void VisBaseCollection::target(float x, float y)
{
    isTargeting = true;
    dynX->setValue( pos().x() );
    dynY->setValue(pos().y() );
    dynX->setTarget( x );
    dynY->setTarget( y );
}

//set to new position, no dynamic targeting
void VisBaseCollection::setValues( float x, float y )
{
    dynX->setValue( x );
    dynY->setValue( y );
    setPos( x, y );
    update();
}


void VisBaseCollection::advance()
{
    if( !isTargeting )
        return;

    if( dynX->isTargeting() )
    {
        dynX->update();
        setPos( dynX->value, pos().y() );
    }

    if( dynY->isTargeting() )
    {
        dynY->update();
        setPos( pos().x(), dynY->value );
    }

    isTargeting = dynX->isTargeting() || dynY->isTargeting()
                    || dynWidth->isTargeting() || dynHeight->isTargeting() ;

    update();

    parentItem()->update();
}

QRectF VisBaseCollection::boundingRect() const
{
    return QRectF(-1.0*dynWidth->value/2.0, -1.0*dynHeight->value/2.0, dynWidth->value, dynHeight->value );
}

QPainterPath VisBaseCollection::shape() const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}


void VisBaseCollection::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    painter->setBrush( Qt::blue );
    painter->drawEllipse( boundingRect() );
}

QRectF VisBaseCollection::centerXCenterYRect() const
{
    return QRectF(-1.0*dynWidth->value/2.0, -1.0*dynHeight->value/2.0, dynWidth->value, dynHeight->value );
}

QRectF VisBaseCollection::centerXTopYRect() const
{
    return QRectF(-1.0*dynWidth->value/2.0, 0.0, dynWidth->value, dynHeight->value );

}

QRectF VisBaseCollection::leftXCenterYRect() const
{
    return QRectF(0.0, -1.0*dynHeight->value/2.0, dynWidth->value, dynHeight->value );
}

QRectF VisBaseCollection::leftXTopYRect() const
{
    return QRectF(0.0, 0.0, dynWidth->value, dynHeight->value );
}

